package com.jumi.microservice.material.controller;

import com.github.pagehelper.PageInfo;
import com.jumi.common.log.annotation.Log;
import com.jumi.common.log.enums.BusinessType;
import com.jumi.microservice.common.base.AjaxResult;
import com.jumi.microservice.common.base.BaseController;
import com.jumi.microservice.common.base.dto.ResponseResult;
import com.jumi.microservice.common.constant.RequestConstant;
import com.jumi.microservice.common.excel.utils.ExcelUtils;
import com.jumi.microservice.material.domain.JmMaterialAttributeResp;
import com.jumi.microservice.material.domain.JmMaterialAttributeVo;
import com.jumi.microservice.material.service.ExcelService;
import com.jumi.microservice.material.service.JmMaterialAttributeService;
import com.jumi.microservice.material.service.JmMaterialAttributeValueService;
import com.jumi.microservice.material.utils.DownloadUtil;
import com.jumi.microservice.warehouseout.utils.PoiUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

/**
 * <p>
 * 商品属性 前端控制器
 * </p>
 *
 * @author ZhangY
 */
@RestController
@RequestMapping("/attr")
@CrossOrigin
@Slf4j
@Api(tags = {"【基础资料】商品属性接口"})
public class JmMaterialAttributeController extends BaseController
{



	@Autowired
	private JmMaterialAttributeService jmMaterialAttributeService;

	@Autowired
	private JmMaterialAttributeValueService jmMaterialAttributeValueService;

	@Autowired
	private ExcelService excelService;

	/**
	 * 添加一条
	 */
	@Log(title = "供应链管理-基础管理-物料属性",businessType = BusinessType.INSERT)
	@ApiOperation("增加")
	@RequestMapping(method = RequestMethod.POST)
	public AjaxResult add(JmMaterialAttributeVo attrVo, @RequestHeader(RequestConstant.ADMIN_NAME) String createBy)
	{
		attrVo.setCreateBy(createBy);
		attrVo.setUpdateBy(createBy);
		int result = jmMaterialAttributeService.add(attrVo);
		if (result == 0)
		{
			return AjaxResult.error("已存在相同属性名称");
		}
		if (result == -1)
		{
			return AjaxResult.error("同一属性下不允许添加相同的属性值");
		}
		return AjaxResult.success(attrVo.getAttrId());
	}

	/**
	 * 修改一条(属性修改时:只能增加属性值,原有属性值不可变动.)
	 */
	@Log(title = "供应链管理-基础管理-物料属性",businessType = BusinessType.UPDATE)
	@ApiOperation("修改")
	@RequestMapping(method = RequestMethod.PUT)
	public AjaxResult update(String sttrValuesString, String attrId, @RequestHeader(RequestConstant.ADMIN_NAME) String updateBy)
	{
		if (sttrValuesString == null || sttrValuesString.length() <= 0)
		{
			return AjaxResult.success("编辑无变动");
		}
		int result = jmMaterialAttributeService.update(sttrValuesString, attrId, updateBy);
		if(result==-1)
		{
			return AjaxResult.error("修改时添加的属性值中有重复");
		}
		if(result==-2)
		{
			return AjaxResult.error("修改时添加的属性的属性值在数据库中已存在");
		}
		return AjaxResult.success(attrId);
	}

	/**
	 * 批量删除
	 */
	@Log(title = "供应链管理-基础管理-物料属性",businessType = BusinessType.DELETE)
	@ApiOperation("批量删除")
	@RequestMapping(method = RequestMethod.DELETE)
	public AjaxResult deleteById(String attrIds, @RequestHeader(RequestConstant.ADMIN_NAME) String updateBy)
	{
		String[] ids = attrIds.split(",");
		int result = jmMaterialAttributeService.deleteByIds(ids, updateBy);
		if (result == 0)
		{
			return AjaxResult.error("存在启动状态的属性,不能删除");
		}
		return AjaxResult.success("删除成功");
	}

	/**
	 * 修改状态
	 */
	@Log(title = "供应链管理-基础管理-物料属性",businessType = BusinessType.UPDATE)
	@ApiOperation("根据Id修改状态")
	@RequestMapping(value = "/setStatus/{attrId}/{attrStatus}", method = RequestMethod.PUT)
	public AjaxResult setStatus(@PathVariable Integer attrId, @PathVariable Integer attrStatus, @RequestHeader(RequestConstant.ADMIN_NAME) String updateBy)
	{
		jmMaterialAttributeService.setStatus(attrId, attrStatus, updateBy);
		return AjaxResult.success(attrId);
	}

	/**
	 * 根据Id查询
	 */
	@ApiOperation("根据Id查询")
	@ApiImplicitParam(name = "attrId", value = "id值", required = true)
	@RequestMapping(value = "/{attrId}", method = RequestMethod.GET)
	public AjaxResult findById(@PathVariable Integer attrId)
	{
		JmMaterialAttributeResp attr = jmMaterialAttributeService.findById(attrId);
		return AjaxResult.success(attr);
	}

	/**
	 * 条件+分页查询
	 */
	@ApiOperation("条件查询+分页")
	@RequestMapping(value = "/findAll", method = RequestMethod.GET)
	public AjaxResult search(JmMaterialAttributeVo materialAttributeVo)
	{
		PageInfo<JmMaterialAttributeResp> page = jmMaterialAttributeService.findPage(materialAttributeVo);
		if(page==null){
			return AjaxResult.success(new HashMap());
		}
		return AjaxResult.success(page);
	}

	/**
	 * 根据attrId查询属性值集合
	 */
	@ApiOperation("根据attrId查询属性值集合")
	@RequestMapping(value = "/findValuesByAttrIds", method = RequestMethod.GET)
	public AjaxResult findValuesByAttrIds(String attrIds)
	{
		ArrayList<Object> valuesByAttrIds = jmMaterialAttributeValueService.findValuesByAttrIds(attrIds);
		return AjaxResult.success(valuesByAttrIds);
	}

	/**
	 * 获取新增属性的id
	 */
	@ApiOperation("获取新增属性的id")
	@RequestMapping(value = "/getAttrValueId", method = RequestMethod.GET)
	public AjaxResult getAttrValueId(String attrId, String attrValueName, @RequestHeader(RequestConstant.ADMIN_NAME) String createBy)
	{
		int id = jmMaterialAttributeValueService.getAttrValueId(attrId, attrValueName, createBy);
		return AjaxResult.success(id);
	}

	/**
	 * @Description: Excel批量导出
	 */
	@ApiOperation("属性Excel导出")
	@RequestMapping(value = "/getAttrExcel",method = RequestMethod.GET)
	public void getAttrExcel(HttpServletResponse response) throws IOException {
		List<JmMaterialAttributeResp> list = jmMaterialAttributeService.findAll();
		if(list!=null && !list.isEmpty())
		{
			for (JmMaterialAttributeResp resp : list)
			{
				resp.setAttributeValues(null);
				resp.setAttrStatusString(null);
			}
		}
		ExcelUtils<JmMaterialAttributeResp> util = new ExcelUtils<>(JmMaterialAttributeResp.class);
		util.exportExcel(response,list, "物料属性信息");
	}

	/**
	 * @Description: Excel批量导入属性  -- EasyExcel
	 */
	@ApiOperation("Excel批量导入属性")
	@PostMapping("/importAttrs")
	@Log(title = "供应链管理-基础管理-物料属性",businessType = BusinessType.INSERT)
	public ResponseResult importAttrs(HttpServletRequest request, @RequestHeader(RequestConstant.ADMIN_NAME) String createBy)
	{
		Long uid = getUid();
		return excelService.excelAttrsImport(request,uid,createBy);
	}

	/**
	 * @Description: Excel批量导入属性  -- POI
	 */
	//@ApiOperation("Excel批量导入属性")
	//@PostMapping("/importAttrsByPoi")
	//@Log(title = "供应链管理-基础管理-物料属性",businessType = BusinessType.INSERT)
	public ResponseResult importExcel(MultipartFile file, @RequestHeader(RequestConstant.ADMIN_NAME) String createBy) throws IOException
	{
		InputStream inputStream = file.getInputStream();
		Workbook workbook = new XSSFWorkbook(inputStream);
		Sheet sheet = workbook.getSheetAt(0);
		Row row = sheet.getRow(0);
		Object[] objs = new Object[row.getLastCellNum()];

		ArrayList<JmMaterialAttributeVo> attributeVoList = new ArrayList<>();
		for (int i = 1; i <= sheet.getLastRowNum(); i++)
		{
			row = sheet.getRow(i);
			for (int j = 0; j < row.getLastCellNum(); j++)
			{
				Cell cell = row.getCell(j);
				Object obj = PoiUtils.getCellValue(cell);
				objs[j] = obj;
			}
			//不同对象的构造方法需要根据Excel模板内容顺序进行构造.
			attributeVoList.add(new JmMaterialAttributeVo(objs));
		}

		ArrayList<String> samedAttrNameList = jmMaterialAttributeService.findSamedAttrName(attributeVoList);
		if (samedAttrNameList != null && !samedAttrNameList.isEmpty())
		{
			return ResponseResult.error(500, "批量插入失败,以下属性已存在:", samedAttrNameList);
		}
		else
		{
			for (JmMaterialAttributeVo attributeVo : attributeVoList)
			{
				attributeVo.setCreateBy(createBy);
				jmMaterialAttributeService.add(attributeVo);
			}
			return ResponseResult.success();
		}
	}

	/**
	 * @Description: Excel属性模板下载  -- POI
	 */
	@ApiOperation("Excel属性模板下载")
	@GetMapping("/downLoadTemplate")
	public void downLoadTemplate(HttpServletResponse response) throws IOException
	{
		Workbook workbook = new XSSFWorkbook();

		//任何一个单元格对象都可以指定使用该单元格样式对象
		CellStyle cellStyle = workbook.createCellStyle();
		cellStyle.setBorderBottom(BorderStyle.THIN);
		cellStyle.setBottomBorderColor(IndexedColors.BLUE.getIndex());
		Font font = workbook.createFont();
		font.setFontHeightInPoints((short) 16);
		cellStyle.setFont(font);

		//表1
		Sheet sheet = workbook.createSheet("属性上传表");
		sheet.setColumnWidth(1,15 * 256);
		sheet.setColumnWidth(2,30 * 256);
		Row row = sheet.createRow(0);
		Cell cell1 = row.createCell(0);
		Cell cell2 = row.createCell(1);
		cell1.setCellValue("属性名");
		cell1.setCellStyle(cellStyle);
		cell2.setCellValue("属性值名");
		cell2.setCellStyle(cellStyle);

		//下载
		ByteArrayOutputStream bos = new ByteArrayOutputStream();
		workbook.write(bos);
		new DownloadUtil().download(bos,response,"属性上传模板.xlsx");
	}
}
